// pages/userInfoCenter/index.js

const App = getApp();
const {Dialog, Toast} = require("../../../../../config/modal")
const utils = require("../../../../../utils/util")
const {LOCATION} = require("../../../../../config/login.js")
import deviceUtil from "../../../../../UI/lin-ui/dist/utils/device-util"

Page({
    /**
     * 页面的初始数据
     */
    data: {
        theamTextColor: App.globalData.theamTextColor,
        capsuleBarHeight: App.$getMenuButtonHeight(),
        file: {
            maxSize: 5242880,
            maxCount: 6,
            list: []
        },
        datetimePicker: {
            show: false,
            minDate: new Date().getTime() + (30 * 60 * 1000),
            maxDate: new Date(2031, 10, 1).getTime(),
            currentDate: new Date().getTime() + (30 * 60 * 1000),
        },
        task: {
            id: '',
            content: "",
            remark: "",
            serviceFees: '5',
            schoolName: '',
            effectivTime: '',
            urgentState: 'normal'
        },
        rules:
            {
                content: {
                    msg: "请输入内容",
                    required: true,
                },
                serviceFees: {required: true, val: '', msg: "酬劳"},
                effectivTime: {val: "", msg: "失效时间", required: true},
            },
            startDongTai: App.$getActionFlag(),
    },
    URL: {
        save: "/task/publish",
        update: "/task/updateTask",
    },
    page: {
        article: '/pages/tabbar/dynamic/list/index',
        taskCenter: "/pages/tabbar/index/robOrders/index",
        userEdit:'/pages/tabbar/user/userInfoEdit/index'
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.hideShareMenu();
        utils.saveFromPage(App, getCurrentPages());

        // 编辑
        if (!utils.isInvalid(options.item)) {
            let item = JSON.parse(options.item);
            this.setData({
                'task': item,
            })
        }
        this.setData({
            startDongTai:App.$getActionFlag()
        })
    },
    onShow() {
        // 检测是否授权
        this.setData({
            'task.schoolName': utils.isInvalid(App.$getUserInfo().schoolName)?'-':App.$getUserInfo().schoolName
        })
        if (utils.isInvalid(this.data.task.schoolName)) {
            wx.showToast({
                title:'请先完善个人资料哦～',
                icon:'none',
                duration:1000
            })
        }
        this.setDefaultTime()
    },
    setDefaultTime() {
        let timestamp = new Date().getTime();//当前的时间戳
        timestamp = timestamp + 1 * 60 * 60 * 1000;
        //格式化时间获取年月日
        var dateAfter = new Date(timestamp);
        let a = dateAfter.getFullYear() + '-' + (dateAfter.getMonth() + 1) + '-' + dateAfter.getDate() + ' ' + dateAfter.getHours() + ':' + dateAfter.getMinutes() + ":" + dateAfter.getSeconds();
        this.setData({
            'task.effectivTime': a
        })
    },

    // 获取胶囊额导航栏的高度
    getNavigationBarHeight() {
        const capsuleBarHeight = deviceUtil.getNavigationBarHeight();
        this.setData({
            'capsuleBarHeight': capsuleBarHeight
        })
        // console.log(`CapsuleBar 的高度为${capsuleBarHeight}rpx`)
    },
    onNormalChange(e) {
        let v = 'normal'
        if (e.detail) {
            v = 'urgent';
        }
        this.setData({
            'task.urgentState': v
        })
    },

    onInputChange(e) {
        let val = e.detail
        let key = e.currentTarget.dataset.name;
        if (key === "content") {
            val = val.value;
        }
        let keyName = 'task.' + key
        let ruleKey = 'rules.' + key + '.val';
        if (key === "serviceFees") {
            if (!utils.checkIsNum(val) && val !== '') {
                this.setData({
                    [ruleKey]: '输入错误'
                })
                return;
            } else {
                this.setData({
                    [ruleKey]: ''
                })
            }
        } else {
            if (val !== '') {
                this.setData({
                    [ruleKey]: ''
                })
            }
        }
        this.setData({
            [keyName]: val
        })
    },
    // 时间选择器
    onInput(e) {
        let timestamp = e.detail;
        let d = new Date(timestamp);    //根据时间戳生成的时间对象
        let date = (d.getFullYear()) + "-" +
            (d.getMonth() + 1) + "-" +
            (d.getDate()) + " " +
            (d.getHours()) + ":" +
            (d.getMinutes()) + ":" +
            (d.getSeconds() === 0 ? '00' : d.getSeconds());
        this.setData({
            'task.effectivTime': date
        })
    },
    onConfirm(e) {
        this.onInput(e);
        this.closePopup();
    },
    showPopup() {
        this.setData({
            'datetimePicker.show': true,
        })
    },
    closePopup() {
        this.setData({
            'datetimePicker.show': false,
        })
    },
    // 提交地址信息
    submitInfo() {
        if (utils.isInvalid(this.data.task.schoolName)) {
            Toast('请先完善个人资料哦～')
            Dialog.alert({
                title: '友情提示',
                message: '请先完善个人资料哦～',
                width: "250px",
                confirmButtonColor: "#D2691E",
                confirmButtonText: "去完善资料",
                showCancelButton: true,
                cancelButtonText: "取消",
            }).then(() => {
                App.$navigateTo(this.page.userEdit, true)
            })
            return;
        }

        let task = this.data.task;
        let rules = this.data.rules;
        let errors = 0;
        for (const key in task) {
            if (Object.hasOwnProperty.call(task, key)) {
                const val = task[key];
                if (!utils.isInvalid(rules[key]) && rules[key].required && utils.isInvalid(val)) {
                    let ruleKey = 'rules.' + key + '.val'
                    this.setData({
                        [ruleKey]: rules[key].msg
                    })
                    ++errors;
                }
            }
        }
        if (errors > 0) {
            return;
        }

        let url = this.URL.save;
        if (!utils.isInvalid(this.data.task.id)) {
            url = this.URL.update;
        }


        App.$post(true, url, this.data.task, res => {
            if (res.R) {
                Dialog.alert({
                    message: res.msg,
                    width: "250px",
                    confirmButtonColor: "#D2691E",
                    confirmButtonText: "确定",
                }).then(() => {
                    App.$redirectTo(utils.getFromPage(App, getCurrentPages()), false);
                })
            }
        })
    },

    save() {
        App.$post(true, this.URL.save, this.data.article, res => {
            this.reqResult(res);
        })
    }
    ,
    update() {
        App.$post(true, this.URL.update, this.data.address.item, res => {
            this.reqResult(res);
        })
    }
    ,
    reqResult(res) {
        if (res.R) {
            Dialog.alert({
                message: '发布成功，回去看看',
                width: "250px",
                confirmButtonColor: "#D2691E",
                confirmButtonText: "确定",
            }).then(() => {
                this.goBack();
            })
        }
    }


    , goBack() {
        wx.navigateBack();
    }
    ,

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    }
    ,


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
    ,

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
    }
    ,

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    }
    ,

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
